package com.glorysoft.tonglingxjpda.ui.function.viewmodel

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.databinding.ObservableArrayList
import com.bumptech.glide.Glide
import com.glorysoft.hlgdpda.entity.ui.CallObserveBean
import com.glorysoft.tonglingxjpda.entity.ui.ToastMessageBean
import com.glorysoft.tonglingxjpda.R
import com.glorysoft.tonglingxjpda.base.BaseViewModel
import com.glorysoft.tonglingxjpda.base.Constant
import com.glorysoft.tonglingxjpda.entity.DefectCodeEntity
import com.glorysoft.tonglingxjpda.entity.DefectEntity
import com.glorysoft.tonglingxjpda.entity.KyhEntity
import com.glorysoft.tonglingxjpda.model.TaskRepository
import com.glorysoft.tonglingxjpda.utils.FileUtils
import com.glorysoft.tonglingxjpda.utils.SmbFileUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import jcifs.smb.SmbFile
import me.tatarka.bindingcollectionadapter2.BR
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.io.File
import kotlin.concurrent.thread

/**
 * FileName: DefectViewModel
 * Author: XJH
 * Date: 2021/7/20 11:41
 * Description:
 * History:
 */
class DefectViewModel : BaseViewModel() {

    val kyhListTitle = arrayListOf("部件描述","刻印号","原厂料号","清洗次数","清洗属性")
    private val defectRepository = TaskRepository()

    private val onCurrentIconClickListener = object : OnItemClickListener{
        override fun onItemClick(item: Any) {
            defUI.callObserve.value = CallObserveBean(2,item)
        }

    }

    private val onHistoryIconClickListener = object : OnItemClickListener{
        override fun onItemClick(item: Any) {
//            val bundle = Bundle()
//            val entity = item as DefectEntity.DefectInfoEntity
//            bundle.putString("PATH",entity.localPath)
//            defUI.startActivity.value = bundle

            defUI.callObserve.value = CallObserveBean(3,item)
        }

    }

    var partItems = ObservableArrayList<KyhEntity.ComponentEntity>()
    var partBinding =
        ItemBinding.of<KyhEntity.ComponentEntity>(BR.partItem, R.layout.item_part_list)

    var currentDefectItems = ObservableArrayList<DefectEntity.DefectInfoEntity>()
    var currentDefectBinding =
        ItemBinding.of<DefectEntity.DefectInfoEntity>(BR.defectItem, R.layout.item_defect_list).bindExtra(BR.onIconClick,onCurrentIconClickListener)


    var historyDefectItems = ObservableArrayList<DefectEntity.DefectInfoEntity>()
    var historyDefectBinding =
        ItemBinding.of<DefectEntity.DefectInfoEntity>(BR.defectItem, R.layout.item_defect_list).bindExtra(BR.onIconClick,onHistoryIconClickListener)
    private val handler = Handler(Looper.getMainLooper())

    var defectDesc = arrayListOf<String>()
    var defectPos = arrayListOf<String>()
    var defectNum = arrayListOf<String>()
    var docID : String = ""


    fun init(id : String){
        docID = id
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","BADINFO")
        map.addProperty("DOCID",id)
        if (partItems.isNotEmpty()){
            map.addProperty("LOTRRN",partItems[0].LOTRRN)
        }

        launchOnlyResult({
            val defectInfo = defectRepository.getDefectInfo(map)
            downPic(defectInfo)
        })
    }

    private fun downPic(defectInfo: DefectEntity) {
        defUI.callObserve.value = CallObserveBean(1,"FAIL")
        thread {
            if(defectInfo.BADINFOLIST.isNotEmpty()){
                defectInfo.BADINFOLIST.forEach {
                    if (it.URL.isNotEmpty()){
                        if (SmbFileUtils.smbGet(it.URL, FileUtils.getLocalPathAndFileName(getApplication()))) {
                            val remoteFile = SmbFile(it.URL)
                            val fileName = remoteFile.name
                            it.localPath = FileUtils.getLocalPathAndFileName(getApplication()) + File.separator + fileName
                        }
                    }
                }
            }
            if(defectInfo.BADINFOHISLIST.isNotEmpty()){
                defectInfo.BADINFOHISLIST.forEach {
                    if (it.URL.isNotEmpty()){
                        if (SmbFileUtils.smbGet(it.URL, FileUtils.getLocalPathAndFileName(getApplication()))) {
                            val remoteFile = SmbFile(it.URL)
                            val fileName = remoteFile.name
                            it.localPath = FileUtils.getLocalPathAndFileName(getApplication()) + File.separator + fileName
                        }
                    }
                }
            }

            handler.post {
                currentDefectItems.clear()
                historyDefectItems.clear()
                currentDefectItems.addAll(defectInfo.BADINFOLIST)
                historyDefectItems.addAll(defectInfo.BADINFOHISLIST)
                defUI.callObserve.value = CallObserveBean(0,"FAIL")
            }
        }

    }

    fun getDefectCode() {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","BAD")
        map.addProperty("USERNAME",Constant.CURRENT_USER)
        map.addProperty("DOCID",docID)
        launchOnlyResult({
            val defectCode = defectRepository.getDefectCode(map)
            defectCode.BADCODE.forEach {
                defectDesc.add(it.NAME)
            }
            defectCode.BADLOCATION.forEach {
                defectPos.add(it.NAME)
            }
            defectCode.BADNUMBER.forEach {
                defectNum.add(it.NAME)
            }
        })
    }

    fun addDefect(code : String,pos : String,num : String,path : String){
        val fileName = docID + FreeApi_DateUtils.getNowStringDate("yyyyMMddHHmmssSSS")
        if (path.isEmpty()){
            saveDefect(code,pos,num,"")
        }else{
            thread {
                if (SmbFileUtils.smbUpload(
                        path,
                        fileName
                    )
                ) {
                    saveDefect(code,pos,num,"${SmbFileUtils.remoteUrl}$fileName.jpg")
                }else{
                    handler.post {
                        defUI.toastEvent.value = ToastMessageBean("图片上传失败",false)
                        defUI.callObserve.value = CallObserveBean(0,"FAIL")
                    }
                }
            }
        }
    }

    fun deleteDefect(item : DefectEntity.DefectInfoEntity){
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","BADDEL")
        map.addProperty("BADRRN",item.BADRRN)
        launchOnlyResult({
            defectRepository.deleteDefect(map)
            currentDefectItems.remove(item)
        })
    }

    fun saveDefect(code : String, pos : String, num : String, path : String){
        val entity = DefectEntity.DefectInfoEntity()
        entity.BADDES = code
        entity.BADLOC = pos
        entity.BADQTY = num
        entity.URL = path
        if (partItems.isNotEmpty()){
            entity.KYH = partItems[0].COMPONENTALIAS
            entity.LOTRRN = partItems[0].LOTRRN
        }
        val map = JsonObject()
        map.addProperty("ACTIONTYPE","BADSAVE")
        map.addProperty("POID",docID)
        map.add("BADINFO", JsonParser().parse(Gson().toJson(entity)).asJsonObject)
        launchOnlyResult({
            defectRepository.saveDefect(map)
            defUI.toastEvent.value = ToastMessageBean("添加成功",true)
            defUI.callObserve.value = CallObserveBean(0,"SUCCESS")
            init(docID)
        })

    }

    interface OnItemClickListener {
        fun onItemClick(item: Any)
    }
}